//
//  FileUnit.m
//  FreeTime
//
//  Created by 王江华 on 16/8/26.
//  Copyright © 2016年 SRDZ.com. All rights reserved.
//

#import "FileUnit.h"

@implementation FileUnit

+(FileUnit *)shareInstance{
    static FileUnit *unit;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        unit = [[self alloc] init];
        [unit createPathInDocumentDirectory];
    });
    return unit;
}
/**
 *  创建缓存文件夹
 */
-(void)createPathInDocumentDirectory{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *diskCachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"ImageCache"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:diskCachePath]) {
        NSError *error = nil;
        [[NSFileManager defaultManager] createDirectoryAtPath:diskCachePath
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:&error];
    }
}

/**
 *  获取沙盒中的文档目录
 *
 *  @param fileName 文件名字
 *
 *  @return 目录
 */
-(NSString *)pathInDocumentDirectory:(NSString *)fileName{
    NSArray *fileArr = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDirectory = [[fileArr objectAtIndex:0]stringByAppendingPathComponent:@"ImageCache"];
    return [cacheDirectory stringByAppendingPathComponent:fileName];
}

/**
 *  判断缓存中是否有图片
 *
 *  @param url 图片的路径
 *
 *  @return 是否存在
 */
-(BOOL)hasCachedImage:(NSURL *)url{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:[self pathForUrl:url]]) {
        return YES;
    }else{
        return NO;
    }
}

/**
 *  根据获取图片名字
 *
 *  @param url 图片的路径
 */
-(NSString *)pathForUrl:(NSURL *)url{
    return [self pathInDocumentDirectory:[NSString stringWithFormat:@"meow%lu",[[url description] hash]]];
}

@end
